package net.tngou.tnfs.action;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import net.tngou.tnfs.util.HttpUtil;
import net.tngou.tnfs.util.ImgUtil;


/**
 * 提取图片
 * @author tngou.net
 *
 */
public class ExtAction extends BaseAction {

	
	public void jsonimg() {
		String rurl = request.getParameter("url");
		String prefix = request.getParameter("prefix"); //前缀
		String suffix = request.getParameter("suffix"); //后缀
		String filtersuffix = request.getParameter("filtersuffix"); //过滤后缀
		String title="0";
		try {
			URL url= new URL(rurl);
			Document doc= HttpUtil.get(url.toString());
			if(doc==null){printJson("{\"title\":"+JSON.toJSONString(title)+"}");return;}
			title=doc.title();
			Set<String> set = ImgUtil.Images(url,filtersuffix);
			List<String> list = new ArrayList<String>(set);
			if(StringUtils.isNoneBlank(suffix))
			{
				
					for (int i = 0; i < list.size(); i++) {						
					if(!StringUtils.startsWith(list.get(i), suffix)){
							list.remove(i)	; i--;   	 				                
						}
					}			 
				
			}
			
			if(StringUtils.isNoneBlank(prefix))
			{				
					for (int i = 0; i < list.size(); i++) {
						
					if(	!StringUtils.startsWith(list.get(i), prefix)){
							list.remove(i)	   ; i--;
								                
						}
					}
			}
			
			String json = JSON.toJSONString(list);
			
			
			printJson("{\"title\":"+JSON.toJSONString(title)+",\"list\":"+json+"}");
		} catch (MalformedURLException e) {
			
			printJson("{\"title\":"+JSON.toJSONString(title)+"}");
		}
		
	}
}
